<template>
  <el-dialog title="配置合作单位" :visible.sync="formVisible">
    <el-form ref="dataForm" :model="form"
             label-position="left" size="small"
             label-width="100px" style="width: 400px; margin-left:50px;">
      <el-form-item label="合作单位">
        <el-select v-model="form.partnerList"
                   style="width:100%;" placeholder="请选择"
                   filterable clearable multiple>
          <el-option v-for="item in options.partner"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="formVisible = false">
        取消
      </el-button>
      <el-button type="primary"
                 @click="doUpdate()">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import salesContractApi from '@/api/platformLixinping/salesContract'
import partnerApi from '@/api/platformLixinping/partner'

function initFormBean() {
  let formBean = {
    id: null,
    partnerList: []
  }
  return formBean
}

export default {
  name: 'PartnerSetting',
  data() {
    return {
      options: {
        partner: []
      },
      old: initFormBean(),
      form: initFormBean(),
      formVisible: false
    }
  },
  methods: {
    /**
     * 重置表单
     */
    resetForm() {
      for (const key in initFormBean()) {
        this.form[key] = this.old[key]
      }
    },
    /**
     * 显示表单
     */
    handleShow(id) {
      partnerApi.findOptions({
        q: ''
      }).then(res => {
        this.options.partner = res.data.map(item => ({
          label: item.name,
          value: item.id
        }))
      })
      salesContractApi.fetchPartnerList(id)
        .then(res => {
          this.old = {
            id: id,
            partnerList: res.data
          }
          this.resetForm()
          this.formVisible = true
        })
    },
    /**
     * 执行修改操作
     */
    doUpdate() {
      this.$refs['dataForm'].validate()
        .then(() => salesContractApi.setPartner(this.form.id, this.form.partnerList))
        .then(data => {
          this.formVisible = false
          this.$common.showMsg('success', '配置成功')
          this.$emit('updated', data)
        })
    }
  }
}
</script>

